package cn.rokhdelar.ams.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author Rokhdelar
 * @since 2025/3/21 -- 16:02
 **/
@Component
public class DatabaseMetaObjectHandler implements MetaObjectHandler {
    /**
     * @param metaObject : 元数据封装类对象，用于操作字段、获取表名等信息
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String currentUserName = getCurrentUserName();
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createBy", String.class, currentUserName);

        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateBy", String.class, currentUserName);
    }

    /**
     * @param metaObject : 元数据封装类对象，用于操作字段、获取表名等信息
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String currentUserName = getCurrentUserName();
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateBy", String.class, currentUserName);
    }

    /**
     * 获取当前登录用户名
     * @return 当前登录用户名，如果未登录则抛出异常。
     */
    private String getCurrentUserName(){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            return authentication.getName();
        }
        return "taskUser";
    }
}
